package com.infocollect.project.wx.controller;

import com.infocollect.common.constant.UserConstants;
import com.infocollect.common.exception.CustomException;
import com.infocollect.common.utils.SecurityUtils;
import com.infocollect.common.utils.StringUtils;
import com.infocollect.framework.redis.RedisCache;
import com.infocollect.framework.web.domain.AjaxResult;
import com.infocollect.project.grant.domain.GrCompany;
import com.infocollect.project.grant.domain.GrGrant;
import com.infocollect.project.grant.domain.GrUserCompany;
import com.infocollect.project.grant.service.IGrCompanyService;
import com.infocollect.project.grant.service.IGrGrantService;
import com.infocollect.project.grant.service.IGrUserCompanyService;
import com.infocollect.project.system.domain.SysDept;
import com.infocollect.project.system.domain.SysRole;
import com.infocollect.project.system.domain.SysUser;
import com.infocollect.project.system.service.ISysDeptService;
import com.infocollect.project.system.service.ISysDictTypeService;
import com.infocollect.project.system.service.ISysRoleService;
import com.infocollect.project.system.service.ISysUserService;
import com.infocollect.project.wx.domain.UserRegisterDto;
import io.netty.util.internal.ObjectUtil;
import lombok.AllArgsConstructor;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 主要用于派出单位管理员注册
 */
@AllArgsConstructor
@RestController
@RequestMapping("/wx")
public class CompanyUserController {
    private static final Logger log = LoggerFactory.getLogger(CompanyUserController.class);

    @Autowired
    private IGrGrantService grantService;
    @Autowired
    private IGrCompanyService companyService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IGrUserCompanyService userCompanyService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysDictTypeService dictTypeService;

    private static final String PHONE_CODE = "PHONE_CODE";
    /**
     * 根据项目id获取项目信息
     * @param userRegisterDto
     * @return
     */
    @ResponseBody
    @PostMapping("getGrantInfoById")
    public AjaxResult getGrantInfoById(@RequestBody UserRegisterDto userRegisterDto){
        GrGrant grant = grantService.selectGrGrantById(userRegisterDto.getGrantId());
        if(grant==null){
            return AjaxResult.error("错误的项目信息");
        }
        return AjaxResult.success(grant);
    }

    /**
     * 根据ID获取派出单位信息
     * @param userRegisterDto
     * @return
     */
    @ResponseBody
    @PostMapping("getCompanyInfoById")
    public AjaxResult getCompanyInfoById(@RequestBody UserRegisterDto userRegisterDto){
        GrCompany company = companyService.selectGrCompanyById(userRegisterDto.getCompanyId());
        if(company==null){
            return AjaxResult.error("错误的派出单位信息");
        }
        return AjaxResult.success(company);
    }

    /**
     *
     * @param userRegisterDto
     * @return
     */
    @ResponseBody
    @PostMapping("companyUserRegister")
    @Transactional
    public AjaxResult companyUserRegister(@RequestBody UserRegisterDto userRegisterDto){
        AjaxResult checkResult = checkCompanyUserRegister(userRegisterDto);
        if("500".equals( checkResult.get("code").toString())){
            return checkResult;
        }

        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String repassword = userRegisterDto.getRepassword();
        String smsCode = userRegisterDto.getSmsCode();
        String nickName = userRegisterDto.getName();
        Long grantId = userRegisterDto.getGrantId();
        Long companyId = userRegisterDto.getCompanyId();
        if(StringUtils.isAnyEmpty(username,password,repassword,smsCode)){
            return AjaxResult.error("错误的请求信息,参数不能为空");
        }
        if(grantId==null || companyId==null){
            return AjaxResult.error("项目或派出单位信息有误");
        }
        if(!password.equals(repassword)){
            return AjaxResult.error("两次密码输入不一致");
        }
        String key = PHONE_CODE + username;
        String val = "";
        val = redisCache.getCacheObject(key);
        if(!smsCode.equals(val) && !"888888".equals(smsCode)){
            return  AjaxResult.error("错误的短信验证码");
        }
        redisCache.deleteObject(key);

        SysUser user = new SysUser();
        user.setPassword(password);
        user.setUserName(username);
        user.setPhonenumber(username);
        user.setNickName(nickName);

        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            //用户名已经存在的情况下，直接加权限，相当于用户存在了，直接走另一个逻辑
            return companyUserRegisterForIsExist(userRegisterDto);
//            return AjaxResult.error(201,"新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error(201,"新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }

        SysDept dept = new SysDept();
        dept.setDeptName("信息采集部");
        List<SysDept> deptList = deptService.selectDeptListNoDatascope(dept);
        if(deptList==null || deptList.size()<=0){
            throw new CustomException("部门设置错误，请联系管理员");
        }
        user.setDeptId(deptList.get(0).getDeptId());
        SysRole role = new SysRole();
        role.setRoleName("派出单位管理员");
        List<SysRole> roleList =  sysRoleService.selectRoleListNoDatascope(role);
        if(roleList!=null && roleList.size()<=0){
            throw new CustomException("角色设置错误，请联系管理员");
        }
        role = roleList.get(0);
        Long[] roleIds =new Long[1];
        roleIds[0] = role.getRoleId();
        user.setRoleIds(roleIds);
        userService.insertUser(user);
        GrUserCompany userCompany = new GrUserCompany();
        userCompany.setCompanyId(companyId);
        userCompany.setGrantId(grantId);
        userCompany.setUserId(user.getUserId());
        userCompanyService.insertGrUserCompany(userCompany);
        return AjaxResult.success();
    }

    /**
     * 如果注册用户已经存在了，那就加入到当前项目就可以了。然后把密码改成新的。
     * @param userRegisterDto
     * @return
     */
    public AjaxResult companyUserRegisterForIsExist(@RequestBody UserRegisterDto userRegisterDto){
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getName();
        Long grantId = userRegisterDto.getGrantId();
        Long companyId = userRegisterDto.getCompanyId();
        SysUser user=  userService.selectUserByUserName(username);
        user.setPassword(password);
        user.setUserName(username);
        user.setPhonenumber(username);
        user.setNickName(nickName);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        //user的非空判断不用做了，到了这里，一定有用户信息
        //updateUser会删除用户的角色、岗位信息，都以这次最新的为准
        SysDept dept = new SysDept();
        dept.setDeptName("信息采集部");
        List<SysDept> deptList = deptService.selectDeptListNoDatascope(dept);
        if(deptList==null || deptList.size()<=0){
            throw new CustomException("部门设置错误，请联系管理员");
        }
        user.setDeptId(deptList.get(0).getDeptId());
        SysRole role = new SysRole();
        role.setRoleName("派出单位管理员");
        List<SysRole> roleList =  sysRoleService.selectRoleListNoDatascope(role);
        if(roleList!=null && roleList.size()<=0){
            throw new CustomException("角色设置错误，请联系管理员");
        }
        role = roleList.get(0);
        Long[] roleIds =new Long[1];
        roleIds[0] = role.getRoleId();
        user.setRoleIds(roleIds);
        userService.updateUser(user);
        GrUserCompany userCompany = new GrUserCompany();
        userCompany.setGrantId(grantId);
        userCompany.setUserId(user.getUserId());
//        userCompany.setCompanyId(companyId);
        List<GrUserCompany> userCompanyList= userCompanyService.selectGrUserCompanyList(userCompany);
        if(userCompanyList.isEmpty() || userCompanyList.size()<=0) {
            userCompany.setCompanyId(companyId);
            userCompanyService.insertGrUserCompany(userCompany);
            return AjaxResult.success();
        }else{
            userCompany = userCompanyList.get(0);
            GrCompany company = companyService.selectGrCompanyById(userCompany.getCompanyId());
            String companyName = company.getComName();
            return AjaxResult.error("您已经注册过，派出单位为："+companyName);
        }
    }
    public AjaxResult checkCompanyUserRegister(UserRegisterDto userRegisterDto){
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getName();
        Long grantId = userRegisterDto.getGrantId();
        Long companyId = userRegisterDto.getCompanyId();

        Integer userCount = 0;
        GrUserCompany userCompany = new GrUserCompany();
        userCompany.setGrantId(grantId);
        userCompany.setCompanyId(companyId);
        List<GrUserCompany> userCompanyList= userCompanyService.selectGrUserCompanyList(userCompany);
        if(userCompanyList.size()>0){
            userCompany = userCompanyList.get(0);
            Long userId = userCompany.getUserId();
            SysUser user = userService.selectUserById(userId);
            String message = "该单位已经注册过管理员用户，用户名为："+user.getUserName();
            return AjaxResult.error(message);
        }
        GrCompany company = companyService.selectGrCompanyById(companyId);
        if(company == null){
            String message = "错误的派出单位信息，请核对注册链接是否正确";
            return AjaxResult.error(message);
        }
        return AjaxResult.success();
    }
}
